package com.platform.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpConnectionManager;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.params.HttpClientParams;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.platform.oss.CloudStorageService;
import com.platform.oss.OSSFactory;

public class WxMpArticleUtil {
    private static Logger logger = Logger.getLogger(WxMpArticleUtil.class);

	public static Map<String,String> fetchArticleByWx(String url) throws IOException{
		return fetchArticleByWx(url,true);
	}
	public static Map<String,String> fetchArticleByWx(String url,boolean isDownPic) throws IOException{
		try {
			Document doc = Jsoup
			.connect(url)
			.ignoreContentType(true)
			.timeout(10000)
			.header("User-Agent",
			        "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.131 Safari/537.36")
			.header("Cookie",
					"ABTEST=8|1430710665|v1; SUID=F55370722708930A000000005546E989; PHPSESSID=0hk2d8cl4128niajvb4f4asfq6; SUIR=1430710665; SUID=F55370724FC80D0A000000005546E989; SNUID=D47250532024351871AD39CB21F3D59C; SUV=00EA70CE727053F55546F1207367B700; weixinIndexVisited=1; wuid=AAGjZr7TCQAAAAqUKHWrjwEAkwA=; ld=nAVZ9yllll2qSs4glllllVqpDNtllllltXxFdyllll9lllllxllll5@@@@@@@@@@; usid=pz2gIdtBRiERY8lB; sct=2; wapsogou_qq_nickname=; IPLOC=CN3200")
			.get();
			Map<String,String> article = new HashMap<String,String>();
			logger.info(doc.toString());
			String title = doc.select("#activity-name").first().text();
//			String content = doc.select("#js_content").first().html().replaceAll("data-src", "src");
			String author = doc.select("#js_name").first().text();
			
			Element content = doc.select("#js_content").first();
			Elements imagesDom = doc.select("#js_content img[data-src]");

			if(isDownPic) {
				int i = 0;
				for (Element img : imagesDom) {
					i++;
					String imgUrl = img.attr("data-src");
					img.attr("style", "width:100%;display:block;");
					String newImgUrl = downloadPicture(imgUrl);
					img.attr("src",newImgUrl);
					img.removeAttr("data-src");
//					content = content.replace(imgUrl, newImgUrl);
					if(article.get("imgUrl") == null || i==2) {
						article.put("imgUrl",newImgUrl);
					}
				}
			}
			article.put("title",title);
			article.put("author",author);
			article.put("content",content.html().replaceAll("background-color:\\s+rgb\\(255\\,\\s+255\\,\\s+255\\);", ""));
			Elements pDoms = doc.select("#js_content p");

			for(Element pDom : pDoms) {
				String text = pDom.text();
				if(StringUtils.isNotBlank(text) && text.length() > 10) {
					article.put("firstP", pDom.html());
					article.put("desc", pDom.text());
				}
			}
			return article;
		} catch (Exception e) {
			logger.error(e.getMessage(),e);
			throw e;
		}
        
	}
	
	
	public static void main(String[] args) {
		try {
//			Map<String,String> article = fetchArticleByWx("https://mp.weixin.qq.com/s?__biz=MzU2OTcyNTgyNA==&tempkey=MTAyNV9nSHlSbDg0T3o4Uk9uVTZrZ1Z1VzRyNzlkYnRtSFJxak5Vcm9tNXlrSU9LeDdWVERRV0dHSFd3YVFNMWtaa2ZuUThBQUZtVjJmSU9MYzJjYXpULUFVcTRLaVdjUlhqNU5YUTgzVnJaU3EwSVNkN09wSlJ0Tms5RmQxVGM1V2Rwd1p2VTVBcFNJMU9NdDhCQTRzMkdxaWpJWG1GM002cXZ2alcxU2tnfn4%3D&chksm=7cfb046a4b8c8d7cb5cb86040fcea33617ace005b61d21fab8c2087b3302f4003a56c2abbc37#rd",false);
//			System.out.println(article.get("content"));
//			downloadPicture("https://mmbiz.qpic.cn/mmbiz_png/zmOQ6Qgfh40Grn2KFghhfRzbEs9uYDkHAmq4EL9PsuaicjrSr0D7A5IemLgc07trIAbK64WibdwAlZAtO59cmJQA/640?wx_fmt=png","D:\\larker_workspace\\agl\\img\\","1.png");
			String content = "r;background-color: rgb(255, 255, 255);\">".replaceAll("background-color:\\s+rgb\\(255\\,\\s+255\\,\\s+255\\);", "");
			System.out.println(content);
		
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	/**
	 * 从网络上下载图片
	 */
	public static String downloadPicture(String url) throws HttpException,IOException{
		HttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
		HttpClientParams params = new HttpClientParams();
		params.setContentCharset("UTF-8");
		params.setParameter("User-Agent","Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:50.0) Gecko/20100101 Firefox/50.0");
		HttpClient client = new HttpClient(params, connectionManager);
		GetMethod method = new GetMethod(url);
		int code = client.executeMethod(method);
//		System.out.println(method.getResponseBodyAsString());
//		httpget
//				.setHeader(
//						"User-Agent",
//						"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.1 (KHTML, like Gecko) Chrome/21.0.1180.79 Safari/537.1");
//		httpget
//				.setHeader("Accept",
//						"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
		if (HttpStatus.SC_OK == code) {
			String prefix = ".png";
			if("jpeg".equalsIgnoreCase(url.substring(url.lastIndexOf("=") + 1))) {
				prefix = ".jpg";
			}
			InputStream in = method.getResponseBodyAsStream();
			return OSSFactory.build().upload(in,CloudStorageService.getPath("")+prefix);
		}
		return null;
	}

}
